<?php
/**
 * Translateone Controller for yos_translator Component
 * @package		yos_translator
 * @subpackage	Components
 * @link		http://yopensource.com
 * @author		yopensource
 * @copyright 	yopensource (yopensource@gmail.com)
 * @license		Commercial
 */

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die();
JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR.DS.'tables');
jimport('joomla.filesystem.file');
require_once(JPATH_SITE.DS.'libraries'.DS.'joomla'.DS.'filesystem'.DS.'archive'.DS.'zip.php');
require_once(JPATH_COMPONENT_ADMINISTRATOR.DS.'helpers'.DS.'createdata.php');

/**
 * Translator Extension Controller
 *
 * @package		yos_translator
 * @subpackage	Components
 */
class FVBControllerNews extends FVBController
{

	/**
	 * constructor (registers additional tasks to methods)
	 * @return void
	 */
	function __construct()
	{
		parent::__construct();

		$this->registerTask('new', 'edit');
		$this->registerTask('apply', 'save');
		$this->registerTask('unpublish', 'publish');
	}

	function publish()
	{
		global $mainframe,$option;

		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		$id 	= JRequest::getVar('id', 0, 'get', 'int');
		$cid 	= JRequest::getVar('cid', array(0), 'post', 'array');
		JArrayHelper::toInteger($cid, array(0));

		// Initialize variables
		$db		=& JFactory::getDBO();
		$user	=& JFactory::getUser();
		$uid	= $user->get('id');
		$task 	= JRequest::getCmd('task','news.publish');

		$publish= ($task=='news.publish')?1:0;

		JArrayHelper::toInteger($cid);

		if (count( $cid ) < 1) {
			$action = $publish ? 'publish' : 'unpublish';
			JError::raiseError(500, JText::_( 'Select a content link to '.$action, true ) );
		}

		$cids = implode( ',', $cid );

		$query = 'UPDATE #__FVB_crawler'
		. ' SET published = ' . (int) $publish
		. ' WHERE id IN ( '.$cids.' )'
		. ' AND ( checked_out = 0 OR ( checked_out = '.(int) $uid.' ) )'
		;
		$db->setQuery( $query );
		if (!$db->query()) {
			JError::raiseError(500, $db->getErrorMsg() );
		}

		if (count( $cid ) == 1) {
			// Set the table directory
			JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR.DS.'tables');
			$row =& JTable::getInstance('FVB_Crawler','Table');
			$row->checkin( $cid[0] );
		}

		$mainframe->redirect( "index.php?option=$option&task=linkmanager" );
	}

	function edit(){
		$document 	= &JFactory::getDocument();
		$vType		= $document->getType();
		$vLayout 	= 'form';
		$mName		= 'contentlink';
		// Get/Create the view
		$view = &$this->getView( 'contentlink', $vType);
		// Get/Create the model

		if ($model = &$this->getModel($mName)) {
			// Push the model into the view (as default)

			$view->setModel($model, true);
		}

		// Set the layout
		$view->setLayout($vLayout);

		// Display the view
		$view->display();
	}

	function connect(){
		$link		=	base64_decode(JRequest::getString('link'));
		require_once(JPATH_SITE.DS.'components'.DS.'com_feed_manager'.DS.'helpers'.DS.'HTTPFetcher.php');
		require_once(JPATH_COMPONENT_ADMINISTRATOR.DS.'helpers'.DS.'readfile.php');
		$docURL	=	new Services_Yadis_PlainHTTPFetcher();

		// Get content file
		$file	=	$docURL->get($link);
		if(!$file)
		{
			echo "Fail !";
		} else {
			echo '<iframe src="'.$link.'" id="linkframe" name="linkframe" width="100%" height="300" marginwidth="0" marginheight="0" scrolling="auto" frameborder="0"></iframe>';
		}
		die();
	}
	
	function makesafelink($data, $host){
		$reglink	=	'/(href|src)=["\'](.*?)["\']/i';
		preg_match_all($reglink, $data, $matches);
		for ($i=0; $i<count($matches[0]); $i++){
			$data	=	str_replace($matches[0][$i],$matches[1][$i].'="'.$this->makelink($host, $matches[2][$i]).'"', $data);
		}
		return $data;
	}

	function makelink($host='', $link){
		require_once(JPATH_COMPONENT_ADMINISTRATOR.DS.'helpers'.DS.'onlydomain.php');
		if (preg_match('/^http:\/\/.*/i', $link) || preg_match('/^mailto:.*/i', $link)) {
			return $link;
		} elseif (preg_match('/^\/.*/i', $link)) {
			$referer = parse_url($host);
			$domain = $referer['host'];
			return 'http://'.$domain.$link;
		} else{
			$slash = strrpos($host, '/') + 1;			
			$host	=	substr($host,0, $slash);
			
			return $host.$link;
		}
	}

	function getlinkxml() {
		$link		=	base64_decode(JRequest::getString('link'));
		$options['rssUrl']=$link;
		$options['cache_time']=3600;

		$rssDoc =& JFactory::getXMLparser('RSS', $options);

		if ( $rssDoc == false ) {
			echo '<input type="hidden" id="getlrss" name="getlrss" value="0" />';
			die();
		}

		echo '<input type="hidden" id="getlrss" name="getlrss" value="1" />';
		$items	=	$rssDoc->get_items();
		echo '<input type="hidden" id="totallink" name="totallink" value="'.count($items).'" />';
		foreach ($items as $item) {
			echo '<div class="matchlink" alt="'.$item->get_link().'"><a href="'.$item->get_link().'">'.$item->get_link().'</a></div>';
		}
		die();
	}

	function gettitlexml() {
		$link		=	base64_decode(JRequest::getString('link'));
		$options['rssUrl']=$link;
		$options['cache_time']=3600;

		$rssDoc =& JFactory::getXMLparser('RSS', $options);

		if ( $rssDoc == false ) {
			echo '<input type="hidden" id="gettrss" name="gettrss" value="0" />';
			die();
		}
		echo '<input type="hidden" id="gettrss" name="gettrss" value="1" />';
		$items	=	$rssDoc->get_items();
		echo '<input type="hidden" id="totaltitle" name="totaltitle" value="'.count($items).'" />';
		foreach ($items as $item) {
			echo '<div class="matchtitle" alt="'.$item->get_title().'"><a href="'.$item->get_title().'">'.$item->get_title().'</a></div>';
		}
		die();
	}

	function getlink(){
		$link		=	base64_decode(JRequest::getString('link'));
		$reg		=	base64_decode(JRequest::getString('regexp'));
		$subreg		=	JRequest::getInt('subreg');
		$findreplace=	base64_decode(JRequest::getString('findreplace'));

		require_once(JPATH_SITE.DS.'components'.DS.'com_feed_manager'.DS.'helpers'.DS.'HTTPFetcher.php');
		require_once(JPATH_COMPONENT_ADMINISTRATOR.DS.'helpers'.DS.'readfile.php');
		$docURL	=	new Services_Yadis_PlainHTTPFetcher();

		// Get content file
		$file	=	$docURL->get($link);

		if(!$file)
		{
			echo '<input type="hidden" id="totallink" name="totallink" value="0" />';
		} else {
			if (!@preg_match_all( $reg, $file->body, $matches)) {
				echo '<font color="red"><strong>Invalid RegExp</strong></div>';
				die();
			}
			if (!isset($matches[$subreg])) {
				echo '<font color="red"><strong>Invalid Sub Pattern</strong></div>';
				die();
			}
			echo '<input type="hidden" id="totallink" name="totallink" value="'.count($matches[0]).'" />';
			for ($i =0; $i<count($matches[0]); $i++){
				$safelink	=	$this->makelink($link, $matches[$subreg][$i]);
				$safelink	=	$this->findreplace($safelink, $findreplace);
				echo '<div class="matchlink" alt="'.$safelink.'"><a href="'.$safelink.'">'.$safelink.'</a></div>';
			}

		}
		die();
	}

	function gettitle(){
		$link		=	base64_decode(JRequest::getString('link'));
		$reg		=	base64_decode(JRequest::getString('regexp'));
		$subreg		=	JRequest::getInt('subreg');

		require_once(JPATH_SITE.DS.'components'.DS.'com_feed_manager'.DS.'helpers'.DS.'HTTPFetcher.php');
		require_once(JPATH_COMPONENT_ADMINISTRATOR.DS.'helpers'.DS.'readfile.php');
		$docURL	=	new Services_Yadis_PlainHTTPFetcher();

		// Get content file
		$file	=	$docURL->get($link);

		if(!$file)
		{
			echo '<input type="hidden" id="totaltitle" name="totaltitle" value="0" />';
		} else {

			if (!@preg_match_all( $reg, $file->body, $matches)) {
				echo '<font color="red"><strong>Invalid RegExp</strong></div>';
				die();
			}
			if (!isset($matches[$subreg])) {
				echo '<font color="red"><strong>Invalid Sub Pattern</strong></div>';
				die();
			}
			echo '<input type="hidden" id="totaltitle" name="totaltitle" value="'.count($matches[0]).'" />';
			for ($i =0; $i<count($matches[0]); $i++){
				echo '<div class="matchtitle" alt="'.$matches[$subreg][$i].'">'.$matches[$subreg][$i].'</div>';
			}

		}
		die();
	}

	function findreplaceencode($data, $find_replace){
		$encode		=	array();
		$decode		=	array();
		$arr_reg	=	explode("\n", $find_replace);

		if (trim($arr_reg[0])=='') {
			return $data;
		}

		if (@preg_match_all('/<script.*?>.*?<\/script>/si', $data, $matches)) {
			for ($i = 0; $i<count($matches[0]); $i++){
				array_push($encode, md5($matches[0][$i]));
				array_push($decode, $matches[0][$i]);
				$data = str_replace($matches[0][$i], md5($matches[0][$i]), $data);
			}
		}

		if (@preg_match_all('/(&lt;|<)a\s+.*?href="(.*?)"(&gt;|>)(.*?)(&lt;|<)\/a(&gt;|>)/is', $data, $matches)) {
			for ($i = 0; $i<count($matches[0]); $i++){
				array_push($encode, md5($matches[0][$i]));
				array_push($decode, $matches[0][$i]);
				$data = str_replace($matches[0][$i], md5($matches[0][$i]), $data);
			}
		}

		if (@preg_match_all('/(&lt;|<)img\s.*?src="(.*?)".*?\/(&gt;|>)/i', $data, $matches)) {
			for ($i = 0; $i<count($matches[0]); $i++){
				array_push($encode, md5($matches[0][$i]));
				array_push($decode, $matches[0][$i]);
				$data = str_replace($matches[0][$i], md5($matches[0][$i]), $data);
			}
		}

		foreach ($arr_reg as $findreplace) {
			if (trim($findreplace)!='') {
				$fr		=	explode('<=>', $findreplace);
				$reg 	=	$fr[0];
				$replace=	$fr[1];

				@preg_match_all($reg, $data, $matches);

				for ($i = 0; $i< count($matches[0]); $i++){
					$match	=	$matches[0][$i];
					$data	=	str_replace($match, $replace, $data);
				}
			}
		}

		for ($i =0; $i<count($encode); $i++){
			$data	=	str_replace($encode[$i], $decode[$i], $data);
		}

		return $data;
	}

	function findreplace($data, $find_replace){
		$encode		=	array();
		$decode		=	array();
		$arr_reg	=	explode("\n", $find_replace);

		if (trim($arr_reg[0])=='') {
			return $data;
		}

		foreach ($arr_reg as $findreplace) {
			if (trim($findreplace)!='') {
				$fr		=	explode('<=>', $findreplace);
				$reg 	=	$fr[0];
				$replace=	$fr[1];

				@preg_match_all($reg, $data, $matches);

				for ($i = 0; $i< count($matches[0]); $i++){
					$match	=	$matches[0][$i];
					$data	=	str_replace($match, $replace, $data);
				}
			}
		}

		for ($i =0; $i<count($encode); $i++){
			$data	=	str_replace($encode[$i], $decode[$i], $data);
		}

		return $data;
	}

	function getintro(){
		$link		=	base64_decode(JRequest::getString('link'));
		$reg		=	base64_decode(JRequest::getString('regexp'));
		$subreg		=	JRequest::getInt('subreg');
		$findreplace=	base64_decode(JRequest::getString('findreplace'));
		$findreplaceencode=	base64_decode(JRequest::getString('findreplaceafterencode'));

		require_once(JPATH_SITE.DS.'components'.DS.'com_feed_manager'.DS.'helpers'.DS.'HTTPFetcher.php');
		require_once(JPATH_COMPONENT_ADMINISTRATOR.DS.'helpers'.DS.'readfile.php');
		$docURL	=	new Services_Yadis_PlainHTTPFetcher();

		// Get content file
		$file	=	$docURL->get($link);

		if(!$file)
		{
			echo '<input type="hidden" id="totalintro" name="totalintro" value="0" />';
		} else {

			if (!@preg_match_all( $reg, $file->body, $matches)) {

				echo '<font color="red"><strong>Invalid RegExp</strong></div>';
				die();
			}
			if (!isset($matches[$subreg])) {
				echo '<font color="red"><strong>Invalid Sub Pattern</strong></div>';
				die();
			}
			echo '<input type="hidden" id="totalintro" name="totalintro" value="'.count($matches[0]).'" />';
			for ($i =0; $i<count($matches[0]); $i++){

				$data	=	$this->findreplace($matches[$subreg][$i], $findreplace);
				$data	=	$this->findreplaceencode($data, $findreplaceencode);
				$data	=	$this->makesafelink($data, $link);
				echo '<div class="matchintro">'.htmlspecialchars($data).'</div>';
			}

		}
		die();
	}

	function getintroxml(){
		$link					=	base64_decode(JRequest::getString('link'));
		$findreplace			=	base64_decode(JRequest::getString('findreplace'));
		$findreplaceencode		=	base64_decode(JRequest::getString('findreplaceafterencode'));
		$options['rssUrl']		=	$link;
		$options['cache_time']	=	3600;

		$rssDoc =& JFactory::getXMLparser('RSS', $options);

		if ( $rssDoc == false ) {
			echo '<input type="hidden" id="totalintro" name="totalintro" value="0" />';
			die();
		}
		$items	=	$rssDoc->get_items();
		echo '<input type="hidden" id="totalintro" name="totalintro" value="'.count($items).'" />';
		foreach ($items as $item) {
			$data	=	$item->get_description();
			$data	=	$this->findreplace($data, $findreplace);
			$data	=	$this->findreplaceencode($data, $findreplaceencode);
			$data	=	$this->makesafelink($data, $link);
			echo '<div class="matchintro">'.htmlspecialchars($data).'</div>';
		}
		die();
	}

	function geteachintro(){
		$link		=	base64_decode(JRequest::getString('link'));
		$reg		=	base64_decode(JRequest::getString('regexp'));
		$subreg		=	JRequest::getInt('subreg');
		$findreplace=	base64_decode(JRequest::getString('findreplace'));
		$findreplaceencode=	base64_decode(JRequest::getString('findreplaceafterencode'));

		require_once(JPATH_SITE.DS.'components'.DS.'com_feed_manager'.DS.'helpers'.DS.'HTTPFetcher.php');
		require_once(JPATH_COMPONENT_ADMINISTRATOR.DS.'helpers'.DS.'readfile.php');
		$docURL	=	new Services_Yadis_PlainHTTPFetcher();

		// Get content file
		$file	=	$docURL->get($link);
		if(!$file)
		{
			echo '<font color="red"><strong>Can\'t get data</strong></div>';
		} else {

			if (!@preg_match( $reg, $file->body, $matches)) {

				echo '<font color="red"><strong>Invalid RegExp</strong></div>';
				die();
			}
			if (!isset($matches[$subreg])) {
				echo '<font color="red"><strong>Invalid Sub Pattern</strong></div>';
				die();
			}
			$data	=	$this->findreplace($matches[$subreg], $findreplace);
			$data	=	$this->findreplaceencode($data, $findreplaceencode);
			$data	=	$this->makesafelink($data, $link);
			echo '<div class="matchintro">'.htmlspecialchars($data).'</div>';
		}
		die();
	}

	function geteachfull(){
		$link		=	base64_decode(JRequest::getString('link'));
		$reg		=	base64_decode(JRequest::getString('regexp'));
		$subreg		=	JRequest::getInt('subreg');
		$findreplace=	base64_decode(JRequest::getString('findreplace'));
		$findreplaceencode=	base64_decode(JRequest::getString('findreplaceafterencode'));

		require_once(JPATH_SITE.DS.'components'.DS.'com_feed_manager'.DS.'helpers'.DS.'HTTPFetcher.php');
		require_once(JPATH_COMPONENT_ADMINISTRATOR.DS.'helpers'.DS.'readfile.php');
		$docURL	=	new Services_Yadis_PlainHTTPFetcher();

		// Get content file
		$file	=	$docURL->get($link);
		if(!$file)
		{
			echo '<input type="hidden" id="totalfull" name="totalfull" value="0" />';
		} else {

			if (!@preg_match( $reg, $file->body, $matches)) {

				echo '<font color="red"><strong>Invalid RegExp</strong></div>';
				die();
			}
			if (!isset($matches[$subreg])) {
				echo '<font color="red"><strong>Invalid Sub Pattern</strong></div>';
				die();
			}
			$data	=	$this->findreplace($matches[$subreg], $findreplace);
			$data	=	$this->findreplaceencode($data, $findreplaceencode);
			$data	=	$this->makesafelink($data, $link);
			echo '<div class="matchfull">'.htmlspecialchars($data).'</div>';
		}
		die();
	}
	
	function geteachpage(){
		$link		=	base64_decode(JRequest::getString('link'));
		$reg		=	base64_decode(JRequest::getString('regexp'));
		$subreg		=	JRequest::getInt('subreg');		
		$regtitle	=	base64_decode(JRequest::getString('regexptitle'));
		$subregtitle=	JRequest::getInt('subregtitle');

		require_once(JPATH_SITE.DS.'components'.DS.'com_feed_manager'.DS.'helpers'.DS.'HTTPFetcher.php');
		require_once(JPATH_COMPONENT_ADMINISTRATOR.DS.'helpers'.DS.'readfile.php');
		$docURL	=	new Services_Yadis_PlainHTTPFetcher();

		// Get content file
		$file	=	$docURL->get($link);
		if(!$file)
		{
			echo '<input type="hidden" id="totalpage" name="totalpage" value="0" />';
		} else {

			if (!@preg_match( $reg, $file->body, $matches)) {

				echo '<font color="red"><strong>Invalid RegExp</strong></div>';
				die();
			}
			if (!isset($matches[$subreg])) {
				echo '<font color="red"><strong>Invalid Sub Pattern</strong></div>';
				die();
			}			
			
			$data	=	$matches[$subreg];	
			echo htmlspecialchars($data) .' - ';
			
			if (!@preg_match( $regtitle, $file->body, $matches)) {

				echo '<font color="red"><strong>Invalid RegExp Title</strong></div>';
				die();
			}
			if (!isset($matches[$subregtitle])) {
				echo '<font color="red"><strong>Invalid Sub Pattern Title</strong></div>';
				die();
			}		
			$data	=	$matches[$subregtitle];
			echo '<strong>'.htmlspecialchars($data).'</strong>';
		}
		die();
	}

	function gettype(){
		$link		=	base64_decode(JRequest::getString('link'));
		require_once(JPATH_SITE.DS.'components'.DS.'com_feed_manager'.DS.'helpers'.DS.'HTTPFetcher.php');
		require_once(JPATH_COMPONENT_ADMINISTRATOR.DS.'helpers'.DS.'readfile.php');
		$docURL	=	new Services_Yadis_PlainHTTPFetcher();

		// Get content file
		$file	=	$docURL->get($link);

		if(!$file)
		{
			echo '<input type="hidden" name="type" value="null" />';
		} else {

			if (preg_match('/(xml|rss|atom)/i', $file->headers['Content-Type'])) {
				$type	=	'xml';
			} else {
				$type	=	'html';
			}
			echo '<input type="hidden" name="type" value="'.$type.'" />';
		}
		die();
	}

	function save(){
		global $mainframe;

		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		// Initialize variables
		$db		 		= &JFactory::getDBO();
		$user			= &JFactory::getUser();
		$oldtitle 		= JRequest::getString( 'oldtitle', '', 'post' );
		$post			= JRequest::get( 'post' );

		$config 	= &JComponentHelper::getParams('com_feed_manager');
		$data_type 	= $config->get('data_type');
		
		if ($data_type != 'joomla') {
			if ($post['catid'] > 0) {
				$arr_cat			= explode(',', $post['catid']);
				$post['catid']		= $arr_cat[0];
				$post['catname']	= base64_decode($arr_cat[1]);
			}else 
				$post['catname']	= '';
		}else 
			$post['catname']	= '';
		
		$type			=	JRequest::getString('type');

		// Set the table directory
		JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR.DS.'tables');
		$row =& JTable::getInstance('FVB_Crawler','Table');
		$id	=	JRequest::getInt('id');
		if ($id) {
			$row->load($id);
		}
		if (!$row->bind( $post )) {
			JError::raiseError(500, $row->getError() );
		}

		if ($row->publish_down==JText::_('Never')) {
			$row->publish_down=0;
		}

		if ($type == 'xml') {
			$options['rssUrl']=base64_decode(JRequest::getString('link'));
			$options['cache_time']=3600;

			$rssDoc =& JFactory::getXMLparser('RSS', $options);
			if ( $rssDoc == false ) {
				$msg = JText::_('Error: Feed not retrieved');
				$mainframe->redirect('index.php?option=com_feed_manager&task=linkmanager', $msg);
				return;
			}

			// channel header and link
			$row->title	 	  = $rssDoc->get_title();
			$row->url 		  = $rssDoc->get_link();
			$row->description = $rssDoc->get_description();
			$row->category	  = 1;
		} else {
			$row->category		=	0;
			$row->url			=	base64_decode(JRequest::getString('link'));
		}

		if ($data_type != 'joomla')
			$row->sectionid	= 0;

		if (!$row->store()) {
			JError::raiseError(500, $row->getError() );
		}

		$row->checkin();

		switch ( JRequest::getCmd('task') )
		{
			case 'news.apply':
				$msg = JText::_( 'Changes to Contents Link saved' );
				$mainframe->redirect( "index.php?option=".$post['option']."&task=news.edit&cid[]=". $row->id, $msg );
				break;

			case 'news.save':
			default:
				$msg = JText::_( 'Contents Link saved' );
				$mainframe->redirect( "index.php?option=".$post['option']."&task=linkmanager", $msg );
				break;
		}
	}

	function cancel(){
		global $mainframe,$option;

		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		// Initialize variables
		$db =& JFactory::getDBO();

		// Set the table directory
		JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR.DS.'tables');
		$row =& JTable::getInstance('FVB_Crawler','Table');
		$row->bind( JRequest::get( 'post' ));
		$row->checkin();

		$mainframe->redirect( "index.php?option=$option&task=linkmanager" );
	}

	function remove(){
		global $mainframe, $option;
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		// Initialize variables
		$db 	=& JFactory::getDBO();
		$cid 	= JRequest::getVar('cid', array(0), 'post', 'array');
		JArrayHelper::toInteger($cid);

		if (count( $cid ) < 1) {
			JError::raiseError(500, JText::_( 'Select a Link to delete', true ));
		}

		$cids = implode( ',', $cid );

		if (count( $cid )) {
			$cids = implode( ',', $cid );
			$query = 'DELETE FROM #__FVB_crawler'
			. ' WHERE id IN ( '.$cids.' )'
			;
			$db->setQuery( $query );
			if (!$db->query()) {
				JError::raiseError( 500, $db->stderr() );
				return false;
			}
		}

		$mainframe->redirect( "index.php?option=$option&task=linkmanager" );
	}
	
	function removelink(){
		global $mainframe, $option;
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		// Initialize variables
		$db 	=& JFactory::getDBO();
		$cid 	= JRequest::getVar('cid', array(0), 'post', 'array');
		JArrayHelper::toInteger($cid);

		if (count( $cid ) < 1) {
			JError::raiseError(500, JText::_( 'Select a Link to delete', true ));
		}

		$cids = implode( ',', $cid );

		if (count( $cid )) {
			$cids = implode( ',', $cid );
			$query = 'DELETE FROM #__yos_content_link'
			. ' WHERE id IN ( '.$cids.' )'
			;
			$db->setQuery( $query );
			if (!$db->query()) {
				JError::raiseError( 500, $db->stderr() );
				return false;
			}
		}

		$mainframe->redirect( "index.php?option=$option&task=linkcheck" );
	}
	
	function removelinkarticle(){
		global $mainframe, $option;
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		// Initialize variables
		$db 		=& JFactory::getDBO();
		$cid 		= JRequest::getVar('cid', array(0), 'post', 'array');
		$nullDate	= $db->getNullDate();

		if (count($cid) < 1) {
			$msg =  JText::_('Select an item to delete');
			$mainframe->redirect('index.php?option='.$option.'&task=linkcheck', $msg, 'error');
		}

		// Removed content gets put in the trash [state = -2] and ordering is always set to 0
		$state		= '-2';
		$ordering	= '0';

		$arr_cid	= array();
		foreach ($cid as $id)
			$arr_cid[]	= '\''.$id.'\'';
		
		// Get the list of content id numbers to send to trash.
		$cids = implode(',', $arr_cid);

		$query	= ' SELECT '.$db->nameQuote('articleid').' FROM '.$db->nameQuote('#__yos_content_link')
				. ' WHERE '.$db->nameQuote('id').' IN ('.$cids. ')'
				;
		$db->setQuery($query);		
		$result = $db->loadObjectList();		
		if (empty($result)) {			
			$msg =  JText::_('Article(s) does not exist');
			$mainframe->redirect('index.php?option='.$option.'&task=linkcheck', $msg, 'error');
		}
		
		$query 	= ' DELETE FROM '.$db->nameQuote('#__yos_content_link')
				. ' WHERE '.$db->nameQuote('id').' IN ('.$cids.')'
				;
		$db->setQuery($query);
		if (!$db->query()) {			
			$mainframe->redirect( "index.php?option=$option&task=linkcheck", $db->getErrorMsg());
		}
		
		$arr_id	= array();
		$cids	= null;
		for ($i = 0; $i<count($result); $i++)
			$arr_id[]	= '\''.$result[$i]->articleid.'\'';
			
		$cids = implode(',', $arr_id);
		
		$config 	= &JComponentHelper::getParams('com_feed_manager');
		$data_type 	= $config->get('data_type');
		
		if ($data_type == 'joomla') {
			// Update articles in the database
			$query = ' UPDATE '.$db->nameQuote('#__content')
					.' SET '.$db->nameQuote('state').' = '.(int) $state
					.' , '.$db->nameQuote('ordering').' = '.(int) $ordering
					.' , '.$db->nameQuote('checked_out').' = 0'
					.' , '.$db->nameQuote('checked_out_time').' = '.$db->Quote($nullDate)
					.' WHERE '.$db->nameQuote('id').' IN ('.$cids.')'
					;
			$db->setQuery($query);
			if (!$db->query()) {			
				$mainframe->redirect( "index.php?option=$option&task=linkcheck", $db->getErrorMsg());
			}
	
			$cache = & JFactory::getCache('com_content');
			$cache->clean();
	
			$msg = JText::sprintf('Link(s) deleted, Article(s) sent to the Trash', count($cid));
		}else {
			$option_ 	= array(); //prevent problems
 
			$option_['driver']   = $config->get('d_w_driver');       	// Database driver name
			$option_['host']     = $config->get('d_w_host');    		// Database host name
			$option_['user']     = $config->get('d_w_user');  	    	// User for database authentication
			$option_['password'] = $config->get('d_w_password');  		// Password for database authentication
			$option_['database'] = $config->get('d_w_database');  	  	// Database name
			$option_['prefix']   = $config->get('d_w_prefix');          // Database prefix (may be empty)
			
			if (empty($option_['user']) || empty($option_['password']) || empty($option_['database']))
				$mainframe->redirect( "index.php?option=$option&task=linkcheck", '');
			
			$db_	= &JDatabase::getInstance( $option_ );
			
			if (!empty($db_->message)) {
				$msg = JText::sprintf($db_->message);
				$mainframe->redirect( "index.php?option=$option&task=linkcheck", $msg);
			}
			
			if ($data_type == 'drupal') {
				$query 	= ' DELETE FROM '.$db_->nameQuote('#__node')
						. ' WHERE '.$db_->nameQuote('nid').' IN ('.$cids.')'
						;
				$db_->setQuery($query);
				if (!$db_->query())
					$mainframe->redirect( "index.php?option=$option&task=linkcheck", $db_->getErrorMsg());
				
				$query 	= ' DELETE FROM '.$db_->nameQuote('#__node_revisions')
						. ' WHERE '.$db_->nameQuote('nid').' IN ('.$cids.')'
						;
				$db_->setQuery($query);
				if (!$db_->query())
					$mainframe->redirect( "index.php?option=$option&task=linkcheck", $db_->getErrorMsg());
				
				$query 	= ' DELETE FROM '.$db_->nameQuote('#__node_comment_statistics')
						. ' WHERE '.$db_->nameQuote('nid').' IN ('.$cids.')'
						;
				$db_->setQuery($query);
				if (!$db_->query())
					$mainframe->redirect( "index.php?option=$option&task=linkcheck", $db_->getErrorMsg());
				
				$query 	= ' DELETE FROM '.$db_->nameQuote('#__category_node')
						. ' WHERE '.$db_->nameQuote('nid').' IN ('.$cids.')'
						;
				$db_->setQuery($query);	
				$db_->query();
			}else {
				$query 	= ' DELETE FROM '.$db_->nameQuote('#__wp_posts')
						. ' WHERE '.$db_->nameQuote('ID').' IN ('.$cids.')'
						;
				$db_->setQuery($query);
				if (!$db_->query())
					$mainframe->redirect( "index.php?option=$option&task=linkcheck", $db_->getErrorMsg());
					
				$query 	= ' DELETE FROM '.$db_->nameQuote('#__wp_term_relationships')
						. ' WHERE '.$db_->nameQuote('object_id').' IN ('.$cids.')'
						;
				$db_->setQuery($query);
				if (!$db_->query())
					$mainframe->redirect( "index.php?option=$option&task=linkcheck", $db_->getErrorMsg());
			}
			
			$msg = JText::sprintf('Link(s), Article(s) deleted', count($cid));
		}
		$mainframe->redirect( "index.php?option=$option&task=linkcheck", $msg);
	}

	function plugin(){
		global $mainframe;
		$link			=	base64_decode(JRequest::getString('link'));
		$pid			=	JRequest::getInt('pid');

		$db	=	&JFactory::getDBO();
		$query		=	"SELECT * FROM #__plugins WHERE id = $pid AND published = 1";
		$db->setQuery($query);
		$row	=	$db->loadObject();

		if (!$row) {
			echo '<font color="red"><strong>Invalid Plugin</strong></div>';
			die();
		}

		$param	=	new JParameter($row->params);

		echo '<input type="hidden" name="pluginreglink" value="'.base64_encode($param->get('reglink','')).'" />';
		echo '<input type="hidden" name="pluginsublink" value="'.$param->get('sublink',0).'" />';
		echo '<input type="hidden" name="pluginregtitle" value="'.base64_encode($param->get('regtitle','')).'" />';
		echo '<input type="hidden" name="pluginsubtitle" value="'.$param->get('subtitle',0).'" />';
		echo '<input type="hidden" name="plugindataway" value="'.$param->get('dataway',0).'" />';
		echo '<input type="hidden" name="pluginregintro" value="'.base64_encode($param->get('regintro','')).'" />';
		echo '<input type="hidden" name="pluginsubintro" value="'.$param->get('subintro',0).'" />';
		echo '<input type="hidden" name="pluginfind_replace_intro" value="'.base64_encode($param->get('find_replace_intro','')).'" />';
		echo '<input type="hidden" name="pluginfind_replace_intro_afterencode" value="'.base64_encode($param->get('find_replace_intro_afterencode','')).'" />';
		echo '<input type="hidden" name="pluginregfull" value="'.base64_encode($param->get('regfull','')).'" />';
		echo '<input type="hidden" name="pluginsubfull" value="'.$param->get('subfull',0).'" />';
		echo '<input type="hidden" name="pluginfind_replace_full" value="'.base64_encode($param->get('find_replace_full','')).'" />';
		echo '<input type="hidden" name="pluginfind_replace_full_afterencode" value="'.base64_encode($param->get('find_replace_full_afterencode','')).'" />';

		die();
	}
	
	function backup(){
		global $mainframe;
		$cid 	= JRequest::getVar('cid', array(0), '', 'array');

		JArrayHelper::toInteger($cid, array(0));
		$row	=	&JTable::getInstance('FVB_crawler', 'Table');
		$row->load($cid[0]);
		$row->id	=	null;
		$filename	=	base64_decode($row->link);
		$filename	=	preg_replace('/[\.\:]/i', '', $filename);		
		header("Pragma: public");
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		header("Expires: 0");
		
		header("Content-Transfer-Encoding: binary");
		header('Content-Disposition: attachment;'
		. ' filename="'.$filename.'.xml";'
		. ' modification-date="' . date('Y-m-d H:i:s') . '";'
		); //RFC2183
		header("Content-Type: application/x-download");			// MIME type
		echo $row->toXML();
		die();
	}
	
	function archive() {
		$cid 			= JRequest::getVar('cid', array(0), '', 'array');
		JArrayHelper::toInteger($cid, array(0));
		
		$row			= &JTable::getInstance('FVB_crawler', 'Table');
		$path_archive	= JPATH_COMPONENT_ADMINISTRATOR.DS.'install'.DS;		
		$fileinfos		= array();
		for ($i = 0; $i<count($cid); $i++) {			
			$row->load($cid[$i]);
			$row->id	= null;			
			$host		= parse_url(base64_decode($row->link));
			if (!isset($host['host']))
				continue;
			$filename	= base64_decode($row->link);
			$filename	= preg_replace('/[\.\:]/i', '', $filename);
			$filename	= preg_replace('/[\/\?]/i', '_', $filename);
//			$filename	= preg_replace('/www./i', '', $host['host']);
			$xml_file 	= $path_archive.$filename.'.xml';
			JFile::write($xml_file, $row->toXML());
			
			$fileinfos[$i]['data']	= JFile::read($xml_file);
			$fileinfos[$i]['name']	= $filename.'.xml';
			JFile::delete($xml_file);
		}
		$filename 	= 'FVB_crawler_backup_links';
    	
		$filezip 	= $path_archive.$filename.'.zip';
		$zip 		= new JArchiveZip();
		$zip->create($filezip,$fileinfos);

		header("Pragma: public");
		header("Expires: 0");
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		header("Cache-Control: public");
    	header("Content-Description: File Transfer");		
		header("Content-Type: application/zip");
		header("Content-Disposition: attachment; filename=".basename($filezip).";");
		header("Content-Transfer-Encoding: binary");
		header("Content-Length: ".filesize($filezip));
		@readfile($filezip);
    	exit;
		die();
	}
	
	function overwritedata(){
		global $mainframe;
		
		$database = JFactory::getDBO();
		/* drop tables */
		$query = "DROP TABLE IF EXISTS `#__FVB_crawler`";
		$database->setQuery($query);
		$database->query();
		if ($database->getErrorNum()) {
			echo $database->getErrorMsg();
			return false;
		}	
		
		/* drop tables */
		$query = "DROP TABLE IF EXISTS `#__yos_content_link`";
		$database->setQuery($query);
		$database->query();
		if ($database->getErrorNum()) {
			echo $database->getErrorMsg();
			return false;
		}	
		
		if (!$result = YOSCreateDB::create()) {
			$mainframe->redirect(JRoute::_('index.php?option=com_feed_manager'), 'Can\'t create database');
			return ;
		}
		
		$mainframe->redirect(JRoute::_('index.php?option=com_feed_manager'), 'Clean database successful');
		return ;
	}

}

